package com.lxu.report.service;

import com.lxu.report.entity.*;
import com.lxu.report.entity.bo.ReportDirBO;
import com.lxu.report.mapper.YwReportDirMapper;
import com.lxu.report.mapper.YwReportExpDataMapper;
import com.lxu.report.util.ReportExceptionUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 处理尽职调查-关联方信息，这种特殊情况
 * 表格里面嵌套扩展行，表格需要进行复制，嵌套扩展行也需要扩展
 */
@Service
public class MultipleTableCopyService {

    @Resource
    private TemplateDataAssembleService templateDataAssembleService;

    @Resource
    private YwReportDirMapper ywReportDirMapper;

    @Resource
    private YwReportExpDataMapper ywReportExpDataMapper;

    private Logger logger = LoggerFactory.getLogger(MultipleTableCopyService.class);
    /**
     * 1、找出符合条件的目录；
     * 2、查询出对应数据条数，即表格需要复制的份数；
     * 3、生成对应的数据；
     * 4、生成对应的模板；
     * @param dirs
     */
    @Transactional
    public boolean init(YwReportData ywReportData,List<ReportDirBO> dirs) {
        /**
         * 1、找出符合条件的目录；
         * 条件为：multiple_table_flag为1的记录，这样的数据说明，需要进行整体表格的复制
         */
        List<ReportDirBO> multipleTableDirs =  dirs.stream().filter(ywReportDir -> "1".equals(ywReportDir.getMultipleTableFlag())).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(multipleTableDirs)){
            return false;
        }
        /**
         * 2、查询出对应数据条数，即表格需要复制的份数；
         * 3、生成对应的数据；
         * 4、生成对应的模板；
         */
        multipleTableDirs.forEach( multipleTableDir ->{
            copyDirDataAndGenerateFiles(multipleTableDir.getId(),templateDataAssembleService.executeSql(multipleTableDir.getDataSql(), ywReportData));
        });
        return true;
    }

    /**
     * 生成表格对应的数据及模板
     * @param id
     * @param ids
     */
    @Transactional
    public void copyDirDataAndGenerateFiles(String id, String ids){
        if(StringUtils.isBlank(id) || StringUtils.isBlank(ids)){
            return;
        }
        String[] tableIds = ids.split(",");
        if(tableIds ==null || tableIds.length<=0){
            return;
        }
        YwReportDir ywReportDir = ywReportDirMapper.getById(id);
        YwReportDir temp = null;
        for (String tableId:tableIds) {
            /**
             * 1、生成《客户报告目录配置表》数据
             */
            try {
                 temp = (YwReportDir) ywReportDir.clone();
            } catch (CloneNotSupportedException e) {
                throw new RuntimeException(ReportExceptionUtil.CLONE_ERROR);
            }
            String newId = UUID.randomUUID().toString().replaceAll("-", "");
            temp.setId(newId);
            temp.setDirName(ywReportDir.getDirName()+"-"+tableId);
            temp.setTemplateFilePath(assembleFilePath(ywReportDir.getTemplateFilePath(),tableId));
            temp.setDataSql(null);
            ywReportDirMapper.insert(temp);
            /**
             * 2、生成《客户报告导出数据配置表》数据
             */
            List<YwReportExpData> exps = ywReportExpDataMapper.getByDirId(id);
            if(CollectionUtils.isEmpty(exps)){
                return;
            }
            exps.forEach(exp ->{
                String newExpId = UUID.randomUUID().toString().replaceAll("-", "");
                exp.setId(newExpId);
                exp.setDirId(newId);
                exp.setDataSql(templateDataAssembleService.assembleDynamicSql(exp.getDataSql(),tableId));
                ywReportExpDataMapper.insert(exp);
            });
            /**
             * 3、复制模板文件
             */
            copyDirFile(ywReportDir.getTemplateFilePath(),temp.getTemplateFilePath());
        }
        ywReportDirMapper.delete(id);
        ywReportExpDataMapper.deleteByDirId(id);
    }

    /**
     * 复制本地文件
     * @param originalFilePath 原始文件路径
     * @param newFilePath  新文件路径
     */
    private static void copyDirFile(String originalFilePath,String newFilePath) {
        String baseDir = "e:\\\\files\\\\";
        String sourceFile = baseDir+originalFilePath.substring(9,originalFilePath.length()-3);
        String destFile = baseDir+newFilePath.substring(9,newFilePath.length()-3);
        File file = new File(sourceFile);
        File file2 = new File(destFile);
        if(file2.isFile() && file2.exists()){
            file2.delete();
        }
        if(file.isFile() && file.exists()){
            try {
                Files.copy(file.toPath(), file2.toPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 组装复制后的模板路径
     * @param path
     * @param id
     * @return
     */
    private static String assembleFilePath(String path,String id) {
        if(StringUtils.isBlank(path) || !path.contains("userfiles")){
            return "不可识别路径";
        }
        String fileName = path.substring(path.lastIndexOf("/")+1,path.length()-3);
        if(StringUtils.isBlank(fileName) || fileName.indexOf(".")<=0){
            return "不可识别文件名称";
        }
        String temp = fileName.split("\\.")[0];
        StringBuffer sb = new StringBuffer();
        sb.append(path.substring(0,path.indexOf("."))).append("-").append(id).append(path.substring(path.indexOf(".")));
        return sb.toString();
    }
}
